package com.example.springboot.controller;

import com.example.springboot.annotation.MethodPermission;
import com.example.springboot.common.PageBean.PageBean;
import com.example.springboot.common.Result.Result;
import com.example.springboot.common.utils.ThrowUtil.ThrowUtil;
import com.example.springboot.entity.Role;
import com.example.springboot.service.RoleService;
import com.example.springboot.service.UserService;
import com.example.springboot.service.UserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static com.example.springboot.common.constants.Constants.ROLE_DELETE_ERROR;
import static com.example.springboot.common.constants.Constants.ROLE_UPDATE_ERROR;


@RestController
@RequestMapping("/acl/role")
public class RoleController {

    @Autowired
    public RoleService roleService;

    @Autowired
    public UserService userService;

    @Autowired
    public UserRoleService userRoleService;

    /**
     * 分页查询
     *
     * @param pageNum
     * @param pageSize
     * @param roleName
     * @return
     */
    @MethodPermission("role_query")
    @GetMapping("/{pageNum}/{pageSize}")
    public Result<?> Page(@PathVariable int pageNum, @PathVariable int pageSize, String roleName) {
        PageBean pageBean = roleService.page(pageNum, pageSize, roleName);
        return Result.success(pageBean);
    }

    /**
     * 保存角色
     *
     * @param role
     * @return
     */
    @MethodPermission("role_add")
    @PostMapping("/save")
    public Result<?> add(@RequestBody Role role) {
        roleService.add(role);
        return Result.success();
    }

    /**
     * 更新角色(用户已分配无法更新)
     *
     * @param role
     * @return
     */
    @MethodPermission("role_update")
    @PutMapping("/update")
    public Result<?> update(@RequestBody Role role) {
        List<String> userNames = userRoleService.getUserNameByRoleId(role.getId());
        if (userNames.size() != 0) {
            String userName = String.join(",", userNames);
            return Result.error(userName + ROLE_UPDATE_ERROR);
        } else {
            roleService.update(role);
            return Result.success();
        }
    }

    /**
     * 删除角色(用户已分配无法删除)
     *
     * @param id
     * @return
     */
    @MethodPermission("role_delete")
    @DeleteMapping("/remove/{id}")
    public Result<?> delete(@PathVariable Long id) {
        ThrowUtil.throwIf(id == 1, "超级管理员无法删除");
        List<String> userNames = userRoleService.getUserNameByRoleId(id);
        if (userNames.size() != 0) {
            String userName = String.join(",", userNames);
            return Result.error(userName + ROLE_DELETE_ERROR);
        } else {
            roleService.delete(id);
            return Result.success();
        }
    }
}
